package com.zzf.uibasetpractice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val msgList = ArrayList<Msg>()

    /*
    * lateint
    * 延迟初始化,告诉编译器将在后边初始化这个变量,在调用这个变量的时候就可以不做判空处理
    * 注意:如果在调用变量之前没有完成初始化,那么此时程序会崩溃,所以一定要记得初始化这个变量
    * */
    private lateinit var adapter:MsgAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initMsg()
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager

        //:: 用来判断变量是否已经进行初始化
        if (!::adapter.isInitialized){
            adapter = MsgAdapter(msgList)
        }

        recyclerView.adapter = adapter
        send.setOnClickListener {
            when(it){
                send -> {
                    val content = inputText.text.toString()
                    if (content.isNotEmpty()){
                        val msg = Msg(content,Msg.TYPE_SEND)
                        msgList.add(msg)

                        //当有新消息时,刷新recyclerView的显示
                        adapter.notifyItemInserted(msgList.size - 1)

                        //将RecyclerView定位到最后一行
                        recyclerView.scrollToPosition(msgList.size - 1)

                        //清空输入框中的内容
                        inputText.setText("")
                    }
                }
            }
        }
    }

    private fun initMsg(){
        val msg1 = Msg("Hello guy",Msg.TYPE_RECEIVED)
        msgList.add(msg1)

        val msg2 = Msg("Hello.Who is that?",Msg.TYPE_SEND)
        msgList.add(msg2)

        val msg3 = Msg("This is Tom . Nice talking to you.",Msg.TYPE_RECEIVED)
        msgList.add(msg3)
    }

}